
require 'lyrics_ebook/lyric'
require 'lyrics_ebook/album'
require 'lyrics_ebook/album_manager'
require 'lyrics_ebook/cache_manager'
require 'lyrics_ebook/lyric_download'
require 'lyrics_ebook/mp3_parser'
require 'lyrics_ebook/epub_builder'

# The main class 
#
# Song lyrics are stored in <home>/Lyrics, if exists, 
#  else in <home>/.lyrics_ebook/Lyrics
#
class LyricsEbook

  def initialize
    @cm=CacheManager.new
    @dm=LyricDownload.new
    @mp3_parser=Mp3Parser.new
    @am=AlbumManager.new
  end

  def parse_dir dir
    if dir.nil?
      puts "Dir not set" 
      return 
    end
    @mp3_parser.parse dir
    $stdout.flush
    @am << @mp3_parser.lyrics
    @am.albums.each do |hash_albums|
      hash_albums.values.each do |album|
        puts "Storing album :"+album.to_s
        @cm.store_album album
      end
    end

    download
  end

  def download
    puts "start downloading..."
    total, new, missing=0,0,0
    lyrics=@mp3_parser.lyrics
    lyrics.each do |lyric|
      total+=1
      if lyric.text.nil? && !@cm.get(lyric)
        if @dm.download(lyric)
          @cm.store(lyric)
          new+=1
        else
          missing+=1 
        end
      end
    end
    puts "#{total} songs in total; #{new} just downloaded; #{missing} missing "
  end

  def build epub_name=nil
    epub_name="lyrics-ebook.epub" if epub_name.nil? 
    l2h=EpubBuilder.new
    albums=@cm.get_albums
    albums.each do |album|
      album.lyrics.each{|lyric| @cm.get(lyric) }
    end
    l2h.add_albums albums
    l2h.to_epub epub_name
  end


end


